/**
 * @author: fangchaunzhi
 * @descripition: 数丰智能科技layer管理
 * @date: created in 15:23 2019/9/20
 * @modify: fangchuanzhi.
 */

import sgisMapBase from "./sfgis.map.base";
import sgisTool from "./sfgis.map.tool";
import hlLayer from "./lib/systemlayers/hl.layer";
export default {
  baseLayer: {}, // 底图
  currLayerId: "", // 当前图层id
  baseLayers: [], // 所有图层
  overLayers: [],//所有除底图外的覆盖图层
  mapInformation: [], // 地图图层信息
  ctaMapInformation: {}, // 注记图层信息
  /**
   * 图层初始化
   * @param options
   */
  init(options) {
    this.mapInformation = options.data;
    this.ctaMapInformation = options.cta;
    // ////分割线//////////
    this.initLayer(); // 将其他图层初始化
    // 增加图例控件
    // if (!$('#layerControl').length) {
    //   LayerControl.loadtpl();
    // }
  }, 
    /**
   *  获取底图
   */
  getBaseLayer() {
    return this.baseLayer;
  },
  /**
   * 初始化所有底图
   */
  initLayer() {
    sgisMapBase.getMap().on('load', () => {
      const _this = this;
      for (let i = 0; i < this.mapInformation.length; i++) {
        const layer = this.formatLayer(i);
        _this.baseLayers.push({
          layer,
          layerName: this.mapInformation[i].name,
          layerId: this.mapInformation[i].id,
          layerType: "baselayer"
        });
        // 使用第一个作为底图
        // eslint-disable-next-line eqeqeq
        if (i == 0) {
          _this.baseLayer = layer; // 获取底图图层
          _this.currLayerId = this.mapInformation[0].id; // 当前图层id
          _this.addLayerToMap(sgisMapBase.getMap(), layer);
        }
      }
      sgisTool.init(sgisMapBase.getMap());
      // 添加pock图片
      sgisMapBase.getMap().loadImage('static/images/pages/pa.png', (error, image) => {
        sgisMapBase.getMap().addImage('pa', image);
      });
      sgisMapBase.getMap().loadImage('static/images/pages/pb.png', (error, image) => {
        sgisMapBase.getMap().addImage('pb', image);
      });
      sgisMapBase.getMap().loadImage('static/images/pages/pc.png', (error, image) => {
        sgisMapBase.getMap().addImage('pc', image);
      });
      sgisMapBase.getMap().loadImage('static/images/pages/pd.png', (error, image) => {
        sgisMapBase.getMap().addImage('pd', image);
      });
      sgisMapBase.getMap().loadImage('static/images/pages/pe.png', (error, image) => {
        sgisMapBase.getMap().addImage('pe', image);
      });
      sgisMapBase.getMap().loadImage('static/images/pages/pm.png', (error, image) => {
        sgisMapBase.getMap().addImage('pm', image);
      });
      sgisMapBase.getMap().loadImage('static/images/pages/pn.png', (error, image) => {
        sgisMapBase.getMap().addImage('pn', image);
      });
    });

  }, // 初始化所有图层
  setZIndexUp(layerid) {
    const layer = this.getOverLayerById(layerid);
    layer.setZIndexOffset(1);
    return;
  }, // 未封装
  getOverLayers() {
    return this.overLayers;
  }, // 获取所有除底图外的覆盖图层
  removeOverLayer(layerId,callback) {
    // layerId 删除图层的id
    for (const key in this.overLayers) {
      if (this.overLayers[key].layerId == layerId) {
        // const layerInfo = sgisMapBase.map.overlayerInfos[layerId];
        let layer = sgisMapBase.map.overlayers[layerId];
        let overlayers = sgisMapBase.map.overlayers;
        let type = this.overLayers[key].type;
        // 删除mapbox原生图层方法
        if( type === "heatLayer" || type === "pockingLayer"){
          // 移除热力图(mapbox原生图层)
          let sourceId = layerId + "_source";
          if(layer !== null){
           
            //麻点清除2层
            if(overlayers.hasOwnProperty(layerId+"-clusters")){
              sgisMapBase.map.removeLayer(layerId+"-clusters");
            }
            if(overlayers.hasOwnProperty(layerId+"-cluster-count")){
              sgisMapBase.map.removeLayer(layerId+"-cluster-count");
            }
            var stateDataLayer = sgisMapBase.map.getLayer(layerId);
            if(stateDataLayer){
              sgisMapBase.map.removeLayer(layerId);
            }
            var sourceObject = sgisMapBase.map.getSource(sourceId);
            if(sourceObject){
              sgisMapBase.map.removeSource(sourceId);
            }
          }
          // 移除图层时移除麻点图popup
          $(".pocking-cus").parent().parent().remove();
          $(".pocking-cus-click").parent().parent().remove();
        }else if(type ==="gridLayer"){
          if(layer !== null){
            // 自定义手动移除mapvlayer canvas（暂时）
            var stateDataLayer = sgisMapBase.map.getLayer(layerId);
            stateDataLayer.removeFromMap();
          }
        }else{
          //移除EchartsLayer层方法
          let layerIds = ["themerange","pie","bar","pictogram","gradesymbol","rosediagram","circulargraph","ranking","rangeThemeLayer"]
          if(layerIds.indexOf(layerId) != -1){
            
          }else{
            layer[0].remove();
          }
        }
        this.overLayers.splice(key, 1);
        callback&&callback();
        return;
      }
    }
  }, // 移除其他图层信息
  removeAllOverLayer(){//移除所有覆盖图层
    for (const key in this.overLayers) {
      this.overLayers[key].layer[0].remove();//移除EchartsLayer层方法
      this.overLayers.splice(key, 1);
    }
  },
  // layerControlChange() {
  //   LayerControl.layerChange(this.getOverLayers(), sgisMapBase.getMap());
  // },
  setOverLayers(options) {
    let that = this;
    if (options['show'] === undefined) {
      options.show = true;
    }
    options.layerType = "overlayer";
    let isOnly = false;
    for (const key in that.overLayers) {
      if (that.overLayers[key].layerId == options.layerId) {
        that.removeOverLayer(options.layerId);//先清除相同信息层
        that.overLayers[key] = options;
        isOnly = true;
      }
    }
    if(!isOnly){
      that.overLayers.push(options);
    }
    
  }, // 设置其他图层
  getAllLayersInfo() { 
    return this.baseLayers;
  }, // 获取所有的覆盖图层
  getCurrLayerId(){//获取当前图层id
    return this.currLayerId;
  },
  getLayer(layerid) {
    for (const key in this.baseLayers) {
      if (this.baseLayers[key].layerId === layerid) {
        return this.baseLayers[key];
      }
    }
  }, // 根据layerid获取地图layer
  getOverLayerById(layerid) {
    for (const key in this.overLayers) {
      if (this.overLayers[key].layerId === layerid) {
        return this.overLayers[key];
      }
    }
  }, // 根据layerid获取overLayer
  hideLayer(layerid) {
    const layer = this.getLayer(layerid);
    const map = sgisMapBase.getMap();
    try {
      map.removeLayer(layer);
    } catch (err) {
      console.log(err);
    }
  }, // 隐藏图层
  showLayer(layerid) {
    const layer = this.getLayer(layerid);
    const map = sgisMapBase.getMap();
    layer.addTo(map);
    this.baseLayer = layer;
  }, // 显示图层
  switchBaseLayer(layerId) {
    let key = '';
    for (const index in this.baseLayers) {
      if (this.baseLayers[index].layerId === layerId) {
        key = index;
        break;
      }
    }
    const map = sgisMapBase.getMap();
    //先移除旧的底图
    if(map.getLayer(this.baseLayer.layer.id)){
      map.removeLayer(this.baseLayer.layer.id);
    }
    //移除旧底图的source
    if(map.getSource(this.baseLayer.source.id)){
      map.removeSource(this.baseLayer.source.id);
    }
    // 获取图层
    const baseLayerInfo = this.getBaseLayerInfoByKey(key);
    this.addLayerToMap(map,baseLayerInfo.layer);
    //保存当前底图信息
    this.baseLayer = baseLayerInfo.layer;
    this.currLayerId = baseLayerInfo.layer.mapInformation.id;
  }, // 图层切换
  calMapOptions(key) {
    const zoom = this.mapInformation[key].zoom ?
      this.mapInformation[key].zoom :
      this.mapInformation[key].minzoom;
    const mapContainerOptions = {
      zoom,
      minZoom: this.mapInformation[key].minzoom,
      maxZoom: this.mapInformation[key].maxzoom,
      center: L.latLng([
        this.mapInformation[key].centx,
        this.mapInformation[key].centy
      ])
    };
    return mapContainerOptions;
  }, // 格式化地图参数
  calCRs(key) {
    // if (this.mapInformation[key].customcrs === 0) {
    //   const crs = L.CRS[this.mapInformation[key].crscode];
    //   return crs;
    // } else {
    //   const crs = L.Proj.CRS(this.mapInformation[key].epsgcode, {
    //     origin: this.mapInformation[key].origin,
    //     scaleDenominators: this.mapInformation[key].scaledenominators,
    //     resolutions: this.mapInformation[key].resolutions,
    //     bounds: L.bounds(
    //       this.mapInformation[key].bounds[0],
    //       this.mapInformation[key].bounds[1]
    //     )
    //   });
    //   return crs;
    // }
  }, // 投影坐标系
  formatLayer(key) {
    const type = this.mapInformation[key].server_type;
    const url = this.mapInformation[key].url;
    const sourceId = "base-layer-raster-tiles-" + key;
    const layerId = "base-layer-tiles-" + key;
    const rasterSource = null;
    return {
      source:{
        id:sourceId,
        value:{
          crossOrigin: 'Anonymous',
          // "attribution": "数丰智能科技",
          "type": "raster",
          "tiles": url,
          "rasterSource": this.mapInformation[key].server_type === "REST" ? "iserver" :"",
          "tileSize": 256
        }
      },
      layer:{
        id:layerId,
        value:{
          "id": "base-layer-tiles-" + key,
          "type": "raster",
          "source": "base-layer-raster-tiles-" + key,
          "minzoom": 0,
          "maxzoom": 18
        }
      },
      mapInformation: this.mapInformation[key]
    };
  }, // 格式化图层参数
  getCurrenScale() {
    const SMType = this.mapInformation[this.currLayerId].server_type;
    const map = sgisMapBase.getMap();
    const zoom = map.getZoom();
    switch (SMType) {
      case "REST":
        return this.baseLayer.scales[zoom];
      case "TDT":
        return this.baseLayer.options.crs.scales[zoom];
      case "WMTS":
        return this.baseLayer.options.crs.scales[zoom];
      case "WMS":
        return this.baseLayer.options.crs.scales[zoom];
      case "MAPABC":
        return this.baseLayer.options.crs.scale(map.getZoom());
      case "GOOGLE":
        return this.baseLayer.options.crs.scale(map.getZoom());
      default:
        return;
    }
  }, // 获取地图当前缩放比例
  /**
   * 添加图层到map
   * @param map map对象
   * @param layerInfo layer对象
   */
  addLayerToMap(map, layerInfo) {
    map.addSource(layerInfo.source.id, layerInfo.source.value);
    map.addLayer(layerInfo.layer.value, "baselayer-tag");
    this.addCtaLayerToMap(map, layerInfo);
  },
  // 添加底图对应的注记图层
  addCtaLayerToMap(map, layerInfo) {
    // 先清除一下上次的注记图层
    const lastCtaSource = map.getSource("cta-layer-raster-tiles");
    const lastCtaLayer = map.getLayer("cta-layer-tiles");
    if(lastCtaLayer !== undefined && lastCtaLayer !== null) {
      map.removeLayer("cta-layer-tiles");
    }
    if(lastCtaSource !== undefined && lastCtaSource !== null) {
      map.removeSource('cta-layer-raster-tiles');
    }
    const ctaKey = layerInfo.mapInformation.cta;
    const ctaInfo = this.ctaMapInformation[ctaKey];
    // eslint-disable-next-line eqeqeq
    if (ctaInfo == undefined || ctaInfo == null) {
      return;
    }
    const url = ctaInfo.url;
    const sourceId = "cta-layer-raster-tiles";
    const layerId = "cta-layer-tiles";
    const source = {
      id: sourceId,
      value: {
        crossOrigin: 'Anonymous',
        "type": "raster",
        "tiles": url,
        "rasterSource": ctaInfo.server_type === "REST" ? "iserver" : "",
        "tileSize": 256
      }
    };
    const layer = {
      id: layerId,
      value: {
        "id": "cta-layer-tiles",
        "type": "raster",
        "source": "cta-layer-raster-tiles",
        "minzoom": 0,
        "maxzoom": 18
      }
    };
    map.addSource(source.id, source.value);
    map.addLayer(layer.value);
  },
  /**
   * 根据图层id key获取底图图层信息
   * @param key
   */ 
  getBaseLayerInfoByKey(key){
    for(const num in this.baseLayers){
      const item = this.baseLayers[key];
      if(item.layer.layer.id === "base-layer-tiles-" + key){
        return item;
      }
    }
  }
};
